﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Furion.JsonSerialization;
using Mapster;
using System.Text.RegularExpressions;
using Admin.NET.Application.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.Service.SaModule;

/// <summary>
/// 发货通知单服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 004)]
public class InventoryEvidenceFTZD : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<InventoryEvidenceTZ> evidenveTZRespository;
    private readonly KingdeeUtil _kingdeeUtil;

    public InventoryEvidenceFTZD(SqlSugarRepository<InventoryEvidenceTZ> _evidenveTZRespository,
        KingdeeUtil kingdeeUtil
        )
    {
        evidenveTZRespository = _evidenveTZRespository;
        _kingdeeUtil = kingdeeUtil;
    }

    #region 同步发货通知单到本地
    /// <summary>
    /// 同步发货通知单到本地
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="Bdate"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/samodule/fhtzd/list/{cid}"), AllowAnonymous]
    public async Task<object> SyncFhtzdList(int cid, string Bdate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_samodule_Fhtzd_list");
        if (string.IsNullOrEmpty(Bdate))
            Bdate = DateTime.Now.ToString();

        List<InventoryEvidenceTZ> Fhtzd_List = new ();

        string FilterString = $"FDate >= '{Bdate}' and FDocumentStatus='C' ";
        var list = KingdeeUtil.Query<SAL_DELIVERYNOTICE_Dto>(KingdeeFormConst.SAL_DELIVERYNOTICE, FilterString);

        foreach (var item in list)
        {
            string orderId = item.FBillNo;
            if (!await evidenveTZRespository.IsAnyAsync(x => x.Evidence_Number.Equals(orderId) && x._cid.Equals(cid)))
            {
                double FQty = item.FQty;
                string FMaterialModel = item.FAuxpropID__FF100002__FDataValue;
                string matchString = @"[^0-9]+";
                double utwt = 1;
                if (!string.IsNullOrEmpty(FMaterialModel))
                {
                    if(Regex.IsMatch(FMaterialModel, matchString)){
                        utwt = Convert.ToDouble(Regex.Replace(FMaterialModel, matchString, ""));
                    }
                }
                    

                var childObj = new InventoryEvidenceDetailTZ()
                {
                    Evidence_Number = orderId,
                    Inventory_ID = item.FMaterialID__FNumber,
                    JarModelID = "1",
                    BoxCode = "1",
                    NBOX = 1,
                    Actual_Qty = item.FQty,
                    UMCode = "KG",
                    OrderID = item.FOrderNo,
                    Frowno = item.FOrderSeq.ParseToInt(),
                    Customer_Product_ID = item.FCustMatID__FNumber,
                    Standard_cost = item.FTaxPrice,
                    Price = item.FTaxPrice,
                    PRICETYPE = "产品价",
                    Amount = item.FAmount,
                    NPkg = FQty / utwt,
                    Qty = FQty,
                    Summary = item.FNoteEntry,
                    Unit_weight = utwt,
                    CurrencyType = item.FSettleCurrId__FNumber,
                    VOL = 9,
                    ShippedQty = 0,
                    ShippednPkg = 0,
                    Discount = 0,
                    PackID = FMaterialModel,
                    MakeBeginDate = item.FPRODUCEDATE,
                    EndDate = item.FEXPIRYDATE,
                    CF01 = item.F_asdg_Text1,
                    _cid = cid
                };

                if (Fhtzd_List.Exists(x => x.Evidence_Number.Equals(orderId)))
                {
                    Fhtzd_List.Find(x => x.Evidence_Number.Equals(orderId)).FG_InvDetail.Add(childObj);
                }
                else
                {
                    Fhtzd_List.Add(new InventoryEvidenceTZ
                    {
                        #region 拼接主表字段
                        Evidence_Number = orderId,
                        ContactNum = item.FCustomerID__FNumber,
                        Date = item.FDate,
                        DeptLead = item.FSaleDeptID_FNumber,
                        Salesman = item.FSalesManID_FNumber,
                        Summ = item.FNote,
                        OrderID = item.FOrderNo,
                        Maker = item.FCreatorId,
                        Posted = 1,
                        Poster = item.FCreatorId,
                        Closed = 0,
                        Type = 88,
                        _cid = cid,
                        #endregion

                        #region 拼接子表字段
                        FG_InvDetail = new List<InventoryEvidenceDetailTZ>() { childObj }
                        #endregion

                    });
                }
            }
        }
        if (Fhtzd_List.Count == 0)
            throw Oops.Bah("无可同步的数据或者已存在！");
        //插入BS数据库
        return await evidenveTZRespository.AsInsertable(Fhtzd_List.ToArray())
            //按导航属性插入子表
            .AddSubList(x => x.FG_InvDetail).ExecuteCommandAsync();
    }
    #endregion

    #region 同步销售退货通知单到本地
    /// <summary>
    /// 同步销售退货通知单到本地
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="Bdate"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/samodule/thtzd/list/{cid}"), AllowAnonymous]
    public async Task<object> SyncThtzdList(int cid, string Bdate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_samodule_thtzd_list");
        if (string.IsNullOrEmpty(Bdate))
            Bdate = DateTime.Now.ToString();

        List<InventoryEvidenceTZ> Fhtzd_List = new();
        List<string> CGNo = new();

        string FilterString = $"FDate >= '{Bdate}' and FDocumentStatus='C'";
        var list = KingdeeUtil.Query<SAL_RETURNNOTICE_Dto>(KingdeeFormConst.SAL_RETURNNOTICE, FilterString);
        int row = 0;
        foreach (var item in list)
        {
            string FBillNo = item.FBillNo;
            if (!await evidenveTZRespository.IsAnyAsync(x => x.Evidence_Number.Equals(FBillNo) && x._cid.Equals(cid)))
            {
                double FQty = item.FQty;
                string FMaterialModel = item.FAuxpropID__FF100002__FDataValue;
                double utwt = string.IsNullOrEmpty(FMaterialModel) ? 1 : Convert.ToDouble(Regex.Replace(FMaterialModel, @"[^0-9]+", ""));

                double Npkg = FQty / utwt;
                var childObj = new InventoryEvidenceDetailTZ()
                {
                    Evidence_Number = FBillNo,
                    Inventory_ID = item.FMaterialID__FNumber,
                    JarModelID = "1",
                    BoxCode = "1",
                    NBOX = 1,
                    PackID = item.FAuxpropID__FF100002__FNumber,
                    Actual_Qty = item.FQty,
                    UMCode = "KG",
                    OrderID = item.FOrderNo,
                    Frowno = row++,
                    Customer_Product_ID = item.FMapId__FNumber,
                    Standard_cost = item.FTaxPrice,
                    Price = item.FTaxPrice,
                    PRICETYPE = "产品价",
                    Amount = item.FAmount,
                    NPkg = Npkg,
                    Qty = Npkg,
                    Summary = item.FEntryDescription,
                    Unit_weight = utwt,
                    CurrencyType = item.FSettleCurrId__FNumber,
                    ProjectBatch = item.FLot__FNumber,
                    VOL = 9,
                    ShippedQty = 0,
                    ShippednPkg = 0,
                    Discount = 0,
                    _cid = cid
                };

                if (Fhtzd_List.FirstOrDefault(x => x.Evidence_Number.Equals(FBillNo)) is not null)
                {
                    Fhtzd_List.FirstOrDefault(x => x.Evidence_Number.Equals(FBillNo))?.FG_InvDetail.Add(childObj);
                }
                else
                {
                    Fhtzd_List.Add(new InventoryEvidenceTZ
                    {
                        #region 拼接主表字段
                        Evidence_Number = FBillNo,
                        ContactNum = item.FRetcustId__FNumber,
                        Date = item.FDate,
                        DeptLead = item.FSaleDeptID__FNumber,
                        Salesman = item.FSalesManID__FNumber,
                        Summ = item.FDescription,
                        OrderID = item.FOrderNo,
                        Maker = item.FCreatorId,
                        Posted = 1,
                        Poster = item.FCreatorId,
                        Closed = 0,
                        Type = 100,
                        _cid = cid,
                        #endregion

                        #region 拼接子表字段
                        FG_InvDetail = new List<InventoryEvidenceDetailTZ>() { childObj }
                        #endregion

                    });
                }
            }
        }
        if (Fhtzd_List.Count == 0)
            throw Oops.Bah("无可同步的数据或者已存在！");
        string json = JSON.Serialize(Fhtzd_List);
        //插入BS数据库
        return await evidenveTZRespository.AsInsertable(Fhtzd_List.ToArray())
            //按导航属性插入子表
            .AddSubList(x => x.FG_InvDetail).ExecuteCommandAsync();
    }
    #endregion
}
